package com.auz.datagenerator.publishing.tcpip;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * Server thread used for communication with a set client
 * @param <X> - generic class
 * @author Aurelien Bonnel
 */
public class ServerThread<X> extends Thread {

	private Socket socket;
	private PrintWriter out;
	
	/**
	 * Constructor
	 * @param _socket - the socket to keep track of
	 */
	public ServerThread(Socket _socket) {
		super("ServerThread");
		this.socket = _socket;
	}
	
	/**
	 * Runs this server thread as a separate thread
	 */
	public void run() {
		try {
			out = new PrintWriter(socket.getOutputStream(), true);
			sendRegistered();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Publish the data
	 * @param _x - the data
	 */
	public void publish(X _x) {
		out.println(_x);
	}
	
	/**
	 * Halts this server thread and shuts down the socket
	 */
	public void halt() {
		try {
			out.println("EXIT");
			out.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Sends a registration confirmation message to the client
	 */
	public void sendRegistered() {
		out.println("Registered");
	}
	
}
